//
//  OAuthViewController.swift
//  WBSwift
//
//  Created by 贺瑞 on 2017/8/3.
//  Copyright © 2017年 herui. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: WebViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupNavBar()
    }
    
    func setupNavBar() {
        
        self.navigationController?.navigationBar.tintColor = UIColor.orange
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .done, target: self, action: #selector(leftBtnOnclick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .done, target: self, action: #selector(rightBtnOnclick))
    }
    
    func leftBtnOnclick() {
        dismiss(animated: true, completion: nil)
    }
    
    func rightBtnOnclick() {
        
    }

    
    
}

extension OAuthViewController {
    
    func reqAccessToken(code : String) {
    
        
        let param = ["client_id" : "429458189",
                     "client_secret" : "9a9d18ed7ac7c3d58c0cccc072cba257",
                     "grant_type" : "authorization_code",
                     "redirect_uri" : "http://www.baidu.com",
                     "code" : code ]

        NetWorkTools.post(url: AccessTokenURL, params: param) { (resp, error) in
            
            guard error == nil else {
                HHLog(error)
                return
            }
            guard let result = (resp as? Dictionary<String, Any>) else {
                return
            }
            guard let accessToken = result["access_token"] as? String else {
                return
            }
            guard let uid = result["uid"] as? String else {
                return
            }
            guard let expires_in = result["expires_in"] as? TimeInterval else {
                return
            }

            HHLog(accessToken)
            HHLog(uid)
            HHLog(expires_in)

            self.reqUserInfo(accessToken: accessToken , uid : uid , expiresDate: expires_in)
        }
    }
    func reqUserInfo(accessToken : String, uid : String, expiresDate : TimeInterval) {

        let param = ["access_token" : accessToken, "uid" : uid]

        NetWorkTools.get(url: UserInfoURL, params: param) { (resp, error) in
            guard error == nil else {
                HHLog(error)
                return
            }
            guard let result = (resp as? Dictionary<String, Any>) else {
                return
            }

            let userInfo = UserInfo(keyvalues: result)
            userInfo.expiresDate = Date().timeIntervalSince1970 + expiresDate
            userInfo.accessToken = accessToken
            userInfo.save()
            
            AppDelegate.rootVCSwitch2Welcome()
        }
    }
    
}


extension OAuthViewController {
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let string = request.url?.absoluteString else {
            return true
        }
        
        guard string.contains("code=") else {
            return true
        }
        
        guard let code = string.components(separatedBy: "code=").last else {
            return true
        }
        
        reqAccessToken(code:code)
        return false
    }
}
